import { managerApi } from '@/request'
import { Message } from 'element-ui'
import { mapState } from "vuex"
import { resUnit, MANAGER_ROLE_CODE, TENANT_ROLE_CODE } from '@/const'
export default {
    data(){
        return {
            syncH: false,
            currentPage: 1,
            searchName:'',
            breadcrumbList: [
                {
                    name: 'public',
                    id: '0'
                }
            ],
            activeName: 'public',
            resourcePublic: [],
            loading: true,
            path: this.$route.path.toLocaleUpperCase(),
            clickStep: 1,  //1命名空间2表名3列族名4列名
            tableHead:[
                {
                    first: '命名空间',
                    second: ''
                },
                {
                    first: '表名',
                    second: '列族数'
                },
                {
                    first: '列族名',
                    second: '列数'
                },
                {
                    first: '列名',
                    second: ''
                }
            ],
            HIVEtableHead:[
                {
                    first: '库名',
                },
                {
                    first: '表名',
                },
                {
                    first: '列名',
                }
            ],
            YARNtableHead:[
                {
                    first: '队列名',
                },
                {
                    first: '子队列名',
                }
            ],
            pageIndex: 1,
            pageSize: 10,
            allUserList:[],
            remainTips:'',
            remainFileTIps:'',
            remainSpace: [],
            role:'',
            toggleIndex:0
        }
    },
    mounted(){
        sessionStorage.searchName = '';
        if(this.loginerRole == MANAGER_ROLE_CODE){ //管理员
            this.role = '1';
        } else if(this.loginerRole == TENANT_ROLE_CODE) { //租户
            this.role = '2';
        } else {
            this.role = '3';
        }
    },
    computed: {
        ...mapState(["loginerRole"]),
    },
    methods:{
        // yarn 移动滑块
        slideChange(){
            this.total = 0;
            this.resourcePublic.map(item => {
                this.total += (item.ratio-0);
            })
        },
        // 切换公、私
        handleClick(tab, event) {
            if(this.activeName == 'public'){
                this.breadcrumbList = [
                    {
                        name: 'public',
                        id: '0'
                    }
                ]
            } else {
                this.breadcrumbList = [
                    {
                        name: 'dataspace',
                        id: '0'
                    }
                ]
            }
            if(/HIVE/.test(this.path)||/HBASE/.test(this.path)){
                this.breadcrumbList = [
                    {
                        name: '返回',
                        id: '0'
                    }
                ]
            }
            this.currentPage = 1;
            this.pageIndex = 1;
            this.clickStep = 1;
            this.getResourceList();
        },
        // 点击面包屑
        onClickBread(item,index){
            this.breadcrumbList = this.breadcrumbList.slice(0, index + 1);
            this.pageIndex = 1;
            this.currentPage = 1;
            this.isPowerDisabled = true;
            if(/HDFS/.test(this.path)){
                this.isPowerDisabled = true;
                this.isAdd = true;
                if(this.breadcrumbList.length == 1){
                    this.isAdd = false; //管理员
                }
                if(this.breadcrumbList.length == 2){
                    this.isPowerDisabled = false;
                }
                // 如果没有写权限怎么处理
                if(/write/.test(item.powerList)){
                    this.isPowerDisabled = false;
                }
            }
            if(/HBASE/.test(this.path)){
                if(this.breadcrumbList.length != 1){
                    this.isPowerDisabled = false;
                }
            }
            this.clickStep = index + 1;
            this.getResourceList();
        },
        // 分页获取列表
        handleCurrentChange(val){
            this.pageIndex = val;
            this.currentPage = val;
            this.getResourceList(this.searchName);
        },
        // 每页数量变化
        handleSizeChange(val){
            this.pageSize = val;
            this.pageIndex = 1;
            this.getResourceList();
        },
        // 处理后台返回的目录名
        urlHandle(val){
            let result = val.split('/')
            return result[result.length-1]
        },
        // 点击目录获取详情
        menuDetail(item){
            this.isPowerDisabled = true;
            var obj = {
                name: '',
                id: item.resourceId,
                power: item.powerList
            };
            if(/write/.test(item.powerList)){
                this.isPowerDisabled = false;
            }
            if(/HDFS/.test(this.path)){
                this.isAdd = true; //管理员
                let name = item.url.split('/');
                name = name[name.length-1];
                obj.name = name;
            }
            if(/HBASE/.test(this.path)){
                switch(this.clickStep){
                    case 1: obj.name = item.spaceName;break;
                    case 2: obj.name = item.tableName;break;
                    case 3: obj.name = item.columnFamilyName;break;
                }
            }
            if(/HIVE/.test(this.path)){
                switch(this.clickStep){
                    case 1: obj.name = item.databaseName;break;
                    case 2: obj.name = item.tableName;break;
                    case 3: obj.name = item.columnName;break;
                }
            }
            if(/YARN/.test(this.path)){
                switch(this.clickStep){
                    case 1: obj.name = item.queueName;break;
                    case 2: obj.name = item.queueName;break;
                }
            }
            this.clickStep++;
            this.breadcrumbList.push(obj);
            this.getResourceList();
            console.log(this.clickStep)
        },
        // 获取hdfs资源列表
        getResourceList(name){
            let resId ='';
            this.breadcrumbList.length>0?resId = this.breadcrumbList[this.breadcrumbList.length-1].id:0;
            var data = {
                pageIndex: this.pageIndex,
                pageSize: this.pageSize,
                reqParam: {
                    type: this.activeName == 'public'?'1':this.activeName == 'tenant'?'2':'3',//资源类型,1公共2私有3共享
                    resourceId: resId,
                    resourceName: name
                }
            }
            this.loading = true;
            //请求接口
            if(/HDFS/.test(this.path)){
                managerApi.getResHDFSList(data).then(res=>{
                    this.getListCB(res)
                }).catch(err => {
                    this.loading = false;
                })
            }
            if(/HBASE/.test(this.path)){
                managerApi.getResHBASEList(data).then(res=>{
                    this.getListCB(res)
                }).catch(err => {
                    this.loading = false;
                })
            }
            if(/HIVE/.test(this.path)){
                managerApi.getResHIVEList(data).then(res=>{
                    this.getListCB(res)
                }).catch(err => {
                    this.loading = false;
                })
            }
            if(/YARN/.test(this.path)){
                managerApi.getResYARNList(data).then(res=>{
                    this.getListCB(res)
                }).catch(err => {
                    this.loading = false;
                })
            }
            if(/KAFKA/.test(this.path)){
                managerApi.getResKafkaList(data).then(res=>{
                    this.getListCB(res)
                }).catch(err => {
                    this.loading = false;
                })
            }
        },
        getListCB(res){
            this.resourcePublic = {};
            this.pageinfo.tenantNum = res.count;
            this.pageinfo.currentPage = this.currentPage;
            res.pageList = res.pageList ||[];
            res.pageList.map(item => {
                if(item.powerList&&item.powerList.length>1){
                    item.powerList = item.powerList.split('|').join(',')
                }
            })

            this.resourcePublic = res.pageList;
            this.loading = fasle;
        },
        // 删除资源
        deleteBtn(row){
            this.dialogData.editData = row;
            if(/HDFS/.test(this.path)){
                this.dialogData.operatorTips = '删除 ' + row.url;
            }
            if(/HBASE/.test(this.path)){
                switch(this.clickStep){
                    case 1: this.dialogData.operatorTips = '删除 ' + row.spaceName;break;
                    case 2: this.dialogData.operatorTips = '删除 ' + row.tableName;break;
                    case 3: this.dialogData.operatorTips = '删除 ' + row.columnFamilyName;break;
                }
            }
            if(/HIVE/.test(this.path)){
                switch(this.clickStep){
                    case 1: this.dialogData.operatorTips = '删除 ' + row.databaseName;break;
                    case 2: this.dialogData.operatorTips = '删除 ' + row.tableName;break;
                    case 3: this.dialogData.operatorTips = '删除 ' + row.columnName;break;
                }
            }
            if(/YARN/.test(this.path)){
                this.dialogData.operatorTips = '删除 ' + row.queueName;
            }
            if(/KAFKA/.test(this.path)){
                this.dialogData.operatorTips = '删除 ' + row.topicName;
            }
            this.dialogData.operatorTips += '?';
            this.dialogData.resOperate = true;
            this.dialogData.opeBtn = '3';
        },
        // 获取下级列表
        getUser(query){
            let data;
            let type = this.path.split('/');
            type = type[type.length-1];
            data =  {
                resourceId: this.common.editData.resourceId,
                username: query,
                type: type
            };
            this.loading = true;
            managerApi.getAuthList(data).then(res => {
                this.loading = false;
                let result = res.data.slice(0,10);
                this.allUserList = result||[];
            }).catch(err => {
                this.loading = false;
            })
        },
        // 租户获取租户
        getTenant(query){
            let data;
            let type = this.path.split('/');
            type = type[type.length-1];
            data =  {
                resourceId: this.common.editData.resourceId,
                isTenantGetTen: '1',
                username: query,
                type: type
            };
            this.loading = true;
            managerApi.getAuthList(data).then(res => {
                this.loading = false;
                let result = res.data.slice(0,10);
                this.tenantList = result||[];
            }).catch(err => {
                this.loading = false;
            })
        },
        // 关闭弹窗
        handleClose(done){
            this.$confirm('确认关闭？')
            .then(_ => {
                // this.common.addResourceTab?this.$refs['resourceCon'].resetFields():"";
                if (this.common.addResourceTab) {
                    this.$refs['resourceCon'].resetFields()
                    this.savedCapacity ? '' : this.savedCapacity={}
                    this.savedCapacity.value = 0
                    this.savedCapacity.unit = 2
                    this.unit=2
                    this.savedFileNum = 0
                    this.unUsedFileNum = 0
                }
                done();
            })
            .catch(_ => {});
        },
        // 取消操作 重置form
        cancelBtn(val){
            if(val == 'resourceCon'){
                this.common.addResourceTab = false;
                this.$refs['resourceCon'].resetFields();
                this.savedCapacity ? '' : this.savedCapacity={}
                this.savedCapacity.value = 0
                this.savedCapacity.unit = 2
                this.unit=2
                this.savedFileNum = 0
                this.unUsedFileNum = 0
            }else{
                this.common.resOperate = false;
                this.common.editYARN = false;
                this.idDelete = true;
            }
        },
        // 获取剩余配额
        getRemain(id){
            let parentId = '';
            id=='0'?parentId = id : parentId = this.common.parentId;
            managerApi.getHdfsRemain({parentId:parentId}).then(res => {
                this.remainSpace = res.data;
                this.getRemainTest();
                // this.remainTips = 'HDFS剩余可用空间 ' + res.data[this.unit] + bity;
            })
        },
        getRemainTest(type){
            let space = this.remainSpace;
            let bity = '';
            switch(this.unit){  // 1.MB; 2.GB; 3.TB
                case 1: bity = 'MB'; break; 
                case 2: bity = "GB"; break;
                case 3: bity = 'TB'; break;
                default: break;
            }
            this.remainTips = 'HDFS剩余可用空间 ' + space[this.unit] + bity;
            
            // 在更改下拉框选项时，进行校验
            if (type && type === 'CHANGE') {
                this.$refs['resourceCon'].validateField('capacity')
            }
        },
        // 获取文件剩余量
        getFileRemain(id){
            let parentId = '';
            id=='0'?parentId = id : parentId = this.common.parentId;
            managerApi.getFileNum({parentId:parentId}).then(res => {
                this.unUsedFileNum = res.data;
                this.remainFileTips = 'HDFS最大文件配额 ' + res.data;
            })
        },
        // 成功的回调
        successCB(val,ope,flag){ //val: 1为资源，2为操作；ope为 操作类型1，分配；2分享；3删除
            this.btnDisabled = false;
            Message.success( ope + '成功！');
            if(val == '1'){
                this.common.addResourceTab = false;
                this.common.editYARN = false;
            } else {
                this.common.resOperate = false;
            }
            if(flag == '1'){
                this.$parent.getResourceList(sessionStorage.searchName);
            } else {
                this.$parent.getResourceList();
            } 
        },
        // 搜索按钮
        searchCon(){
            sessionStorage.searchName = this.searchName;
            this.pageIndex = 1;
            this.currentPage = 1;
            this.getResourceList(this.searchName);
        },
        // 资源详情
        resDetail(row){
            this.dialogData.editData = row;
            if(/HDFS/.test(this.path)){
                this.dialogData.editData.name = row.url;
            }
            if(/HBASE/.test(this.path)){
                this.hbaseTabhead(row);
                this.dialogData.editData.name = row.spaceName;
            }
            if(/HIVE/.test(this.path)){
                this.dialogData.editData.name = row.tableName;
            }
            this.dialogData.operatorTips = '资源详情';
            this.dialogData.resOperate = true;
            this.dialogData.opeBtn = '4'; //详情
            this.dialogData.resTypeName = this.activeName;
        },
        // 同步hive资源
        syncResource(){
            let menu = this.breadcrumbList;
            let id = menu[menu.length-1].id;
            let that = this;
            this.syncH = true;
            if(/HIVE/.test(this.path)){
                managerApi.syncHIVE({resourceId:id}).then(res => {
                    // 同步资源后请求列表
                    Message.success("HIVE资源同步成功！")
                    that.syncH = false;
                    that.getResourceList()
                }).catch(err=>{
                    that.syncH = false;
                })
            }
            if(/YARN/.test(this.path)){
                managerApi.syncYARN({resourceId:id,level:menu.length}).then(res => {
                    // 同步资源后请求列表
                    Message.success("YARN资源同步成功！")
                    that.syncH = false;
                    that.getResourceList()
                }).catch(err=>{
                    that.syncH = false;
                })
            }
            if(/KAFKA/.test(this.path)){
                managerApi.syncKAFKA().then(res => {
                    // 同步资源后请求列表
                    Message.success("Kafka资源同步成功！")
                    that.syncH = false;
                    that.getResourceList()
                }).catch(err=>{
                    that.syncH = false;
                })
            }
        },
        // 分配租户
        tenantBtn(row){
            // type为1时指公共；2为私有；3为共享
            // row.powerList?row.powerList = row.powerList.split(','):'';
            this.role==1?localStorage.selectLength = row.tenantList.length:localStorage.selectLength = row.userList.length;
            this.dialogData.editData = row;
            this.dialogData.resOperate = true;
            let type = this.activeName=='public'?'1':this.activeName=='tenant'?'2':this.activeName=='share'?'3':'';
            type=='1'?this.dialogData.operatorTips = '分配资源':type=='2'?this.dialogData.operatorTips = '分配资源':this.dialogData.operatorTips='分配资源';
            this.dialogData.opeBtn = '1'; // 1为分配；2为分享；3删除
            this.dialogData.resType = type;
            this.dialogData.isShare = '0';
            if(/HBASE/.test(this.path)){
                this.hbaseTabhead(row);
                this.dialogData.editData.url = row.spaceName;
            }
            if(/YARN/.test(this.path)){
                this.dialogData.editData.url = row.queueName;
            }
            if(/HIVE/.test(this.path)){
                this.dialogData.editData.url = row.tableName;
            }
            if(/KAFKA/.test(this.path)){
                this.dialogData.editData.url = row.topicName;
            }
        },
        // 分享
        shareBtn(row){
            // type为1时指公共；2为私有；3为共享
            let type = this.activeName=='public'?'1':this.activeName=='tenant'?'2':this.activeName=='share'?'3':'';
            this.dialogData.editData = row;
            this.dialogData.operatorTips = '分享租户资源';
            this.dialogData.resOperate = true;
            this.dialogData.opeBtn = '2'; // 1为分配；2为分享；3删除
            this.dialogData.resType = type;
            this.dialogData.isShare = '1';
            if(/HBASE/.test(this.path)){
                this.hbaseTabhead(row);
                this.dialogData.editData.url = row.spaceName;
            }
            if(/HIVE/.test(this.path)){
                this.dialogData.editData.url = row.tableName;
            }
        },
        // hbase 表头判断
        hbaseTabhead(row){
            if(this.clickStep == 1){
                this.dialogData.label='命名空间'
            } else if(this.clickStep == 2){
                this.dialogData.label='表名'
                row.spaceName = row.tableName
            } else if(this.clickStep == 3){
                this.dialogData.label='列族名'
                row.spaceName = row.columnFamilyName
            } else if(this.clickStep == 4){
                this.dialogData.label='列名'
                row.spaceName = row.columnName
            }
        }
    }
}